<template>
  <div>
    <el-drawer
      :title="textMap[dialogStatus]"
      :visible.sync="visibility"
      size="61%"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="120px"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="项目" prop="goodsCode">
              <span
                v-if="temp.goodsCode"
              >{{ temp.goodsCode }}, {{ temp.goodsAbbr }},
                {{ temp.goodsFullCode }}</span>
              <el-button
                icon="el-icon-thumb"
                size="mini"
                circle
                class="custome-el-button-circle"
                @click="handleOpenSearchProductionGoodsDialog"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产单位" prop="uint">
              <el-select v-model="temp.unit" placeholder="请选择">
                <el-option
                  v-for="(item, index) in unitOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model.trim="temp.memo" />
        </el-form-item>

        <el-form-item label="物料明细" prop="isGoodsListLength">
          <el-button
            icon="el-icon-plus"
            size="mini"
            circle
            class="custome-el-button-circle"
            @click="handleOpenSearchMaterialGoodsDialog"
          />
        </el-form-item>
        <el-form-item>
          <el-table
            v-if="temp.goodsList && temp.goodsList.length > 0"
            ref="table"
            :data="temp.goodsList"
            align="left"
            highlight-current-row
            style="margin: 10px"
          >
            <el-table-column label="物料货号" prop="goodsCode" width="150px" />
            <el-table-column label="物料简称" prop="goodsAbbr" width="150px" />
            <el-table-column
              label="物料识别码"
              prop="goodsFullCode"
              min-width="150px"
            />
            <el-table-column label="每单位生产用量" width="200px">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.count"
                  oninput="value=value.replace(/[^0-9.]/g,
              '')"
                />
              </template>
            </el-table-column>
            <el-table-column label="单位" width="100px">
              <template slot-scope="scope">
                <el-select v-model="scope.row.unit" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in unitOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="80px"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button
                  class="my-but"
                  @click="deleteGoods(scope.row, scope.$index)"
                ><i class="el-icon-remove-outline" />
                </el-button>
              </template>
            </el-table-column> </el-table></el-form-item>
        <el-form-item label="设备">
          <el-button
            icon="el-icon-plus"
            size="mini"
            circle
            class="custome-el-button-circle"
            @click="handleOpenAddEquipment"
          />
        </el-form-item>
        <el-form-item>
          <el-table
            v-if="temp.equipmentList && temp.equipmentList.length > 0"
            :data="temp.equipmentList"
            highlight-current-row
          >
            <el-table-column
              label="设备编号"
              width="100px"
              prop="equipmentCode"
            />
            <el-table-column
              label="设备名称"
              min-width="100px"
              prop="equipmentName"
            />
            <el-table-column label="规格" width="100px" prop="specification" />
            <el-table-column
              label="有效期"
              width="160px"
              prop="expirationDate"
            />
            <!-- <el-table-column label="使用模式" width="150px">
              <template slot-scope="scope">
                <el-radio-group
                  v-model="scope.row.usage"
                  @click.native="pushRadio(scope.row.usage, scope.$index)"
                >
                  <el-radio disabled :label="1">独占</el-radio>
                  <el-radio disabled :label="0">共享</el-radio>
                </el-radio-group>
              </template>
            </el-table-column> -->
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >提交</el-button>
        </el-form-item>
      </el-form>
      <SearchGoods
        :visible.sync="searchGoodsDialogVisible"
        :show-goods-batch="false"
        :immediate="searchGoodsMode === 'productionGoods'"
        @success="handleSearchGoods"
      />
    </el-drawer>
    <AddEquipment
      :visible.sync="equipmentDialogVisible"
      :equipment-status="equipmentStatus"
      :update-equipment-data="temp.equipmentList"
      @update-data="AddData"
    />
  </div>
</template>

<script>
import { saveBom, updateBom } from '@/api/base/bom'

import SearchGoods from '@/components/SearchGoods'
import { bomListPreOptions } from '@/api/base/bom.js'
import AddEquipment from '@/components/AddEquipment'
export default {
  components: { SearchGoods, AddEquipment },
  props: {
    visible: {
      required: true,
      type: Boolean
    },
    currentRow: {
      type: Object,
      default: null
    },
    dialogStatus: {
      require: true,
      type: String,
      default: 'create'
    },
    scope: {
      type: String,
      default: null
    },
    categoryOptions: {
      type: Array,
      default: null
    }
  },
  data() {
    const isLength = (rule, value, callback) => {
      if (this.temp.goodsList.length > 0) {
        callback()
      } else {
        return callback(new Error('物料清单不可为空'))
      }
    }
    const isCodeLength = (rule, value, callback) => {
      if (this.temp.goodsCode) {
        callback()
      } else {
        return callback(new Error('项目不可为空'))
      }
    }
    const isUint = (rule, value, callback) => {
      if (this.temp.unit) {
        callback()
      } else {
        return callback(new Error('单位不可为空'))
      }
    }
    return {
      searchGoodsMode: null,
      temp: {
        goodsList: [],
        scope: 1,
        equipmentList: [],
        unit: 'g'
      },
      rules: {
        goodsCode: [
          { required: true, validator: isCodeLength, trigger: 'blur' }
        ],
        isGoodsListLength: [
          {
            validator: isLength,
            required: true,
            trigger: 'change'
          }
        ],
        count: [
          { required: true, message: '项目货号不能为空', trigger: 'blur' }
        ],
        uint: [{ required: true, validator: isUint, trigger: 'blur' }]
      },
      textMap: {
        update: '修改物料清单',
        create: '新增物料清单'
      },
      loading: false,
      searchGoodsDialogVisible: false,
      unitOptions: null,
      equipmentDialogVisible: false,
      equipmentStatus: false
    }
  },
  computed: {
    visibility: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible(value) {
      if (value && this.dialogStatus === 'create') {
        this.temp = {
          goodsList: []
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    currentRow: {
      handler(value) {
        if (value && this.dialogStatus === 'update') {
          this.temp = Object.assign({}, value)
          this.temp.unit = 'g'
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
      },
      deep: true
    },
    'temp.unit'(data) {
      if (data) {
        this.$refs['dataForm'].clearValidate('uint')
      }
    }
  },
  mounted() {
    bomListPreOptions().then((res) => {
      this.unitOptions = res.data.goodsUnit || []
    })
  },
  methods: {
    createData() {
      this.loading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isCount = this.isTableCount(this.temp.goodsList)
          if (isCount) {
            this.temp.scope = this.scope
            const equipmentList = this.redoEquipmentList(
              this.temp.equipmentList
            )
            const data = this.temp
            data.equipmentList = equipmentList
            saveBom(data)
              .then(() => {
                this.visibility = false
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.$emit('saveData', {})
              })
              .finally(() => {
                this.loading = false
                // this.temp = this.$options.data.temp
              })
          } else {
            this.$message.warning('单位生产用量不可为空')
          }
        }
      })
    },
    redoEquipmentList(data) {
      const newData = []
      if (data && data.length > 0) {
        data.forEach((e) => {
          newData.push({ equipmentId: e.equipmentId })
        })
      }

      return newData
    },
    updateData() {
      this.loading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const isCount = this.isTableCount(this.temp.goodsList)
          if (isCount) {
            updateBom(tempData)
              .then(() => {
                this.visibility = false
                this.$message({
                  message: '更新成功',
                  type: 'success'
                })
                this.$emit('saveData', tempData)
              })
              .finally(() => {
                this.loading = false
              })
          } else {
            this.$message.warning('单位生产用量不可为空')
          }
        }
      })
    },
    handleOpenSearchProductionGoodsDialog() {
      this.searchGoodsMode = 'productionGoods'
      this.searchGoodsDialogVisible = true
      this.$refs['dataForm'].clearValidate('goodsCode')
    },
    handleOpenSearchMaterialGoodsDialog() {
      this.searchGoodsMode = 'materialGoods'
      this.searchGoodsDialogVisible = true
    },
    handleSearchGoods(goods) {
      if (this.searchGoodsMode === 'productionGoods') {
        this.temp.goodsId = goods.goodsId
        this.temp.goodsCode = goods.goodsCode
        this.temp.goodsFullCode = goods.goodsFullCode
        this.temp.goodsAbbr = goods.goodsAbbr
        this.$refs['dataForm'].clearValidate('productionGoodsCode')
      } else {
        let arr = this.temp.goodsList || []
        if (arr.length === 0) {
          arr.push(goods)
          this.$refs['dataForm'].clearValidate(['isGoodsListLength'])
        } else {
          let isId = false
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].goodsId !== goods.goodsId) {
              isId = false
            } else {
              isId = true
              this.$message.warning('数据重复')
              break
            }
          }
          if (!isId) {
            arr.push(goods)
            arr = [...new Set(arr)]
          }
        }

        this.temp.goodsList = Array.from(arr)
      }
      this.searchGoodsMode = null
    },
    view(row) {},
    deleteGoods(row, index) {
      this.temp.goodsList.splice(index, 1)
    },
    resetValidate(row) {},
    /**
     * @description:判断单位生产用量
     * @param {Arr} data
     * @return {}
     */
    isTableCount(data) {
      const newData = data || []
      let isCount = true
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].count) {
          isCount = true
        } else {
          isCount = false
          break
        }
      }
      return isCount
    },
    handleOpenAddEquipment() {
      this.equipmentDialogVisible = true
      this.equipmentStatus = true
    },
    AddData(data) {
      this.temp.equipmentList = Array.from(data)
    }
  }
}

// value=value.replace(/[^0-9.]/g,'')
</script>

<style lang="scss" scoped>
</style>
